import routesPc from "./routesPc";
import routesMB from "./routesMB";
import { pc_rootPath, mobile_rootPath } from "@/router/config.rootPath";

// 获取平台标识
const platform = detectPlatform();
// 平台检测函数（可以根据 User-Agent 或其他逻辑）
function detectPlatform() {
  const userAgent = navigator.userAgent.toLowerCase();
  if (/mobile|android|iphone|ipad/.test(userAgent)) return "mobile";
  return "web"; // 默认为 Web
}

// 获取路由配置
// const handRouter = []

// 移动端
const isMobile = platform == "mobile";
let handRouter = isMobile ? routesMB : routesPc;

// 获取路由组件数组
function generateRoutes() {
  const files = import.meta.glob("@/views/**/*.vue");
  let arr = [];
  Object.entries(files).forEach(([path, component]) => {
    // 移除开头的 @/views/ 和结尾的 .vue
    const cleanedPath = path.replace(/@\/views\//, "").replace(/\.vue$/, "");

    // 组件不需要注册
    let cleanedPathSplit = cleanedPath.split("/");
    if (cleanedPathSplit.includes("components")) return;
    if (cleanedPathSplit.includes("404")) return;

    // 阻拦不同屏幕 screen 的路由
    if (!cleanedPathSplit.includes(screen)) return;

    // 若是最后两个相同则删一个
    const length = cleanedPathSplit.length;
    if (cleanedPathSplit[length - 1] === cleanedPathSplit[length - 2]) {
      cleanedPathSplit.splice(length - 1, 1);
    }

    // 获取注册路由
    const newPath = cleanedPathSplit
      .join("/")
      .replace("/src/views", "")
      .toLowerCase();

    // 获取
    const existRouter = handRouter.map((item) => item.path);

    // 若最终需要注册的路由 已存在则不需要
    if (existRouter.includes(newPath)) return;

    // PC获取不需要注册的主页面
    if (screen == "PC") {
      const obj = handRouter.find((item) => item.path == "/");
      if (obj) {
        const noRegisterRouters = obj.children.map((item) =>
          item.path.toLowerCase()
        );
        if (noRegisterRouters.includes(newPath)) return;
        // console.log(handRouter, newPath);
      }
    }

    // console.log("可注册路由", newPath);
    const routePath = newPath;
    arr.push({
      path: routePath,
      name: newPath.replace(/\//g, "-"),
      component: () => component(),
    });
  });

  return arr;
}

// 自动获取的路由
// const routeList = generateRoutes();
// 最终
// const routes = [...handRouter, ...routeList];

const routes = handRouter;
// console.log("routes", routes);

// 路由根路径
// const rootPath = getRootPath();
// function getRootPath() {
//   if (isMobile) return `/${mobile_rootPath}/`;
//   return `/${pc_rootPath}/`;
// }

import { createRouter, createWebHistory } from "vue-router";
const router = createRouter({
  // 工作模式
  history: createWebHistory("/page/"),
  routes,
});

export default router;
